using System.Collections;
using System.Collections.Generic;
using Unity.Mathematics;
using Unity.VisualScripting;
using UnityEngine;

public class PlayerCtrl : MonoSingleton<PlayerCtrl>
{
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    Rigidbody2D rg;
    // public List<Transform> bkGroup=new List<Transform>();
    public float speedx,deltaV;
    public float maxSpeed;//泡泡的最大速度
    public bool isFly,isPlayerMove,isSpeedFresh;
    public Vector3 standardPos;
    Vector2 inputdir;
    void Start()
    {
        Application.targetFrameRate = 60;
        rg=GetComponent<Rigidbody2D>();
    }
    
    IEnumerator SpeedRefresh()
    {
        print("refresh");
        while(math.abs(rg.linearVelocity.magnitude)<maxSpeed && isSpeedFresh)
        {
            Vector2 dir=(standardPos-transform.position).normalized;
            rg.linearVelocity+=deltaV*Time.deltaTime*dir;
            yield return null;
        }
        
    }
    
    void CheckSpeedFresh()
    {
        
        if(!isSpeedFresh)
        {
            rg.linearVelocity=Vector2.zero;
            isSpeedFresh=true;
            StartCoroutine(SpeedRefresh());
        }
    }
    void GetInput()
    {
        inputdir=Vector2.zero;
        if(Input.GetKey(KeyCode.A))
        {
            inputdir+=new Vector2(-1,0);
        }
        if(Input.GetKey(KeyCode.D))
        {
            inputdir+=new Vector2(1,0);
        }
        if(Input.GetKey(KeyCode.W))
        {
            inputdir+=new Vector2(0,1);
        }
        if(Input.GetKey(KeyCode.S))
        {
            inputdir+=new Vector2(0,-1);
        }
    }
    
    void CheckSpeed()
    {
        if(inputdir!=Vector2.zero)
        {
            isSpeedFresh=false;
            isFly=true;
            if(math.abs(rg.linearVelocityX)<maxSpeed)
            {
                print(inputdir);
                rg.linearVelocityX+=deltaV*Time.deltaTime*inputdir.x;
            }
            if(!(rg.linearVelocityY>maxSpeed && inputdir.y>0||rg.linearVelocityY<-maxSpeed && inputdir.y<0))
            {
                print(inputdir);
                rg.linearVelocityY+=deltaV*Time.deltaTime*inputdir.y;
            }
        }
        else
        {
            isFly=false;
            CheckSpeedFresh();
        }
        if(!isFly)
        {
            speedx=2f;
        }
    }
    void Move()
    {
        if(!isFly)
        {
            if((transform.position-standardPos).magnitude<0.05)
            {
                transform.position=standardPos;
                rg.linearVelocity=Vector2.zero;
                isSpeedFresh=false; 
            }
            
        }
        
    }
    // Update is called once per frame
    void Update()
    {
        GetInput();
        CheckSpeed();
        Move();
    }
}
